package com.tencreat.api.controller;

import com.tencreat.common.core.exception.CustomException;
import com.tencreat.common.core.utils.AddressUtils;
import com.tencreat.common.core.utils.IpUtils;
import com.tencreat.common.core.utils.ServletUtils;
import com.tencreat.common.entity.ImUser;
import com.tencreat.common.service.ImUserService;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public abstract class BaseController {

    @Autowired
    ImUserService userService;

    public ImUser getLoginUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = (Long) authentication.getPrincipal();
        ImUser imUser = userService.getById(userId);
        if(null == imUser){
            throw new CustomException("未知用户!");
        }
        return imUser;
    }
    public boolean updateUserClient(ImUser imuser){
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        boolean update = userService.lambdaUpdate().eq(ImUser::getId, imuser.getId())
                .set(ImUser::getIp, ip)
                .set(ImUser::getLocation, AddressUtils.getRealAddressByIP(ip))
                .set(ImUser::getBrowser, userAgent.getBrowser().getName())
                .set(ImUser::getOs, userAgent.getOperatingSystem().getName())
                .update();
        return update;
    }
}
